package com.zhiyizhen.handheld.common;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加Header
 */
public class HeaderInterceptor implements Interceptor {

    private static final String TOKEN = "token";
    private static final String TIMESTAMP = "timestamp";

    private final Map<String, String> mHeaders = new ConcurrentHashMap<>();

    private static volatile HeaderInterceptor sInstance;

    public static HeaderInterceptor getInstance() {
        if (sInstance == null) {
            synchronized (HeaderInterceptor.class) {
                if (sInstance == null) {
                    sInstance = new HeaderInterceptor();
                }
            }
        }

        return sInstance;
    }

    private HeaderInterceptor() {
    }

    @NonNull
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Request.Builder builder = request.newBuilder();

        final long timestamp = System.currentTimeMillis();
//        final String token = SessionManager.getInstance().getToken();

        builder.addHeader(TIMESTAMP, String.valueOf(timestamp));
//        if (!TextUtils.isEmpty(token)) {
//            builder.addHeader(TOKEN, token);
//        }

        for (Map.Entry<String, String> entry : mHeaders.entrySet()) {
            builder.addHeader(entry.getKey(), entry.getValue());
        }

        return chain.proceed(builder.build());
    }

    public void clearHeaders() {
        if (!mHeaders.isEmpty()) {
            mHeaders.clear();
        }
    }

    public void addHeaders(Map<String, String> headers) {
        mHeaders.putAll(headers);
    }

    public void addHeader(String name, String value) {
        mHeaders.put(name, value);
    }

    public String removeHeader(String name) {
        return mHeaders.remove(name);
    }

    public Map<String, String> getHeaders() {
        return Collections.unmodifiableMap(mHeaders);
    }

    public Map<String, String> getHeader() {
        return mHeaders;
    }
}
